
/**
 * 基于 ZHighlight 的api来实现 AP机考做笔记功能
 * 高亮代码 <zh class="z-highlight pink" data-id="zh-1435820385354" data-notes="This is the content of the notes">This is highlighted content</span>
 * */

const ZH = window.ZHighlight;
//注册一个jquery
ZH.registerJQuery(window.jQuery)

class SATHighlight {
    NODE_NAME = 'span';
    highlightClass = 'z-highlight';
    selectClass = 'z-highlight-select';
    colors = [
        {className: "yellow"},
        {className: "blue"},
        {className: "pink"}
    ]
    highlightNotes = []
    highlightIsActive = false

    constructor(options) {
        this.dom = options.dom

        //注册鼠标事件，用于框选文本
        ZH.registerRootSelectEvent(this.dom, (e) => {
            const el = $(e.target)
            const range = ZH.getRange(5)
            if(!range){
                return  //无效的选择
            }

            if(ZH.selectionContains({
                nodeNames: ['.no-select'],
                styles: ['color: red'],
            })){
                alert('内容包含不能选择的区域')
                ZH.clearSelectRange()
                return;
            }

            const selectNode = this.createWrapperElement();

            const annotation = ZH.wrapSelectContent(this.dom, range, selectNode)
            console.log(annotation)

            ZH.clearSelectRange()

            const dialog = this.showDialog((type) => {
                if(['yellow', 'blue', 'pink'].includes(type) > -1){
                    if(this.currentNode && this.highlightIsActive){
                        const currentEl = this.getNodeElement(this.currentNode.id)
                        if(currentEl){

                        }
                    }else{
                        const node = this.highlightSelectNode(type)
                        annotation.id = node.id
                        annotation.node = node.node
                        annotation.color = node.color
                        annotation.containerElement = node.containerElement
                        this.setHighlightNotes(annotation)
                    }
                    //高亮为黄色
                }else if(type === 'delete'){
                    //删除当前
                }else if(type === 'note'){
                    //笔记
                }
            })

            //显示操作工具框
            const dialogWidth = 300, dialogHeight = dialog.height()
            const pos = ZH.getPosition(e, dialogWidth, dialogHeight, {
                y: dialogHeight,
                x: 0
            })
            dialog.css({left: pos.x + 'px', top: pos.y + 'px', display: 'flex'})
            this.highlightIsActive = true
        })



        $(document.body).on('mousedown touchstart',  () => {
            //清空之前的选区
            ZH.removeTemporary(this.dom, '.' + this.selectClass)
            this.hideDialog()

            if(this.currentNode){
                this.clearHighlightActive(this.currentNode.id)
            }
        })

        //注册一个选区的click事件，用于点击高亮元素
        ZH.registerHighlightNodeClickEvent(this.dom, '.' + this.highlightClass, (e) => {
            console.log('点击一个', e)
        })



    }
    highlightSelectNode(color){
        const nodes = this.dom.getElementsByClassName(this.selectClass)
        console.log(nodes)
        const options = {
            "data-id": ZH.getRandomId(),
            classNames: [this.highlightClass, color, 'active'],
            "data-note": ''
        }
        for (let i = 0; i < nodes.length; i++){
            nodes[i].classList.remove(this.selectClass)
            ZH.setNodeAttribute(nodes[i], options)
        }

        return {
            id: options['data-id'],
            node: options['data-note'],
            color: color,
            containerElement: '#' + this.dom.id
        }
    }
    createWrapperElement() {
        let span = document.createElement(this.NODE_NAME);
        span.classList.add(this.selectClass);
        span.setAttribute("data-id", ZH.getRandomId());
        return span;
    }

    showDialog(mouseup){
        let el = document.getElementById('zh-popover')
        if(el){
            return $(el)
        }
        $(document.body).append(`
        <div id="zh-popover" class="z-highlight-dialog">
              ${
            this.colors.map(item => {
                return `<span class="zh-color ${item.className}"></span>`
            }).join('')
        }
              <div class="highlight-underline"> 
                    <img src="./svg/highlight-underline.svg">
              </div>
              <span class="zh-color delete"><img src="./svg/delete.svg"></span>
              <span class="zh-color note"></span>
        </div>
        `)
        el = document.getElementById('zh-popover')
        $(el).on('mousedown touchstart', function (e){
            e.preventDefault()
            e.stopPropagation()
        })
        this.colors.map(item => {
            $(el).off('mouseup touchend', '.' + item.className)
            $(el).on('mouseup touchend', '.' + item.className, function (e){
                e.target.classList.add('select')
                mouseup(item.className)
            })
        })
        $(el).off('mouseup touchend', '.delete')
        $(el).on('mouseup touchend', '.delete', function (){
            mouseup('delete')
        })
        $(el).off('mouseup touchend', '.note')
        $(el).on('mouseup touchend', '.note', function (){
            mouseup('note')
        })
        return $(el)
    }
    hideDialog(){
        let el = document.getElementById('zh-popover')
        if(el){
            el.style.display = 'none'
        }
    }
    setHighlightNotes(note){
        this.setCurrentNode(note)
        this.highlightNotes.push(note);
    }
    setCurrentNode(note){
        this.currentNode = note;
    }
    getNodeElement(id){
        let node = $(this.NODE_NAME + '[data-id="'+id+'"]')
        return node[0]
    }
    clearHighlightActive(){
        let node = $(this.NODE_NAME + '[data-id="'+id+'"]')
        if(node.length){
            node.removeClass('active')
        }
    }
}

const satighlight  = new SATHighlight({
    dom: document.getElementById('book')
})